<template>
  <!-- 富文本 -->
  <div class="tinymce-container">
    <Editor
      api-key="ge4ymx25w185hf69w12ntcdu4a5x3r2gav7sfp4js5vn81wx"
      v-model="content"
      @change="editorChange"
      id="uuid"
      tag-name="my-custom-tag"
      :init="init"
    />
    <!-- <form method="post">
        <textarea id="mytextarea">Hello, World!</textarea>
    </form> -->
    <!-- <div id="mytextarea"></div> -->
  </div>
</template>

<script setup>
import { defineEmits, reactive, ref, onMounted, onBeforeMount, defineProps, watch } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import axios from 'axios'
import request from 'Common/request/index.js'
import { ElLoading } from 'element-plus'

const appendJsFunction = (url, specialId) => {
  let jsId = document.getElementById(specialId)
  if (jsId == null) {
    var scriptTag = document.createElement('script')
    scriptTag.src = url
    scriptTag.id = specialId
    scriptTag.type = 'text/javascript'
    document.body.appendChild(scriptTag)
  }
}

const emits = defineEmits(['getValue'])
const props = defineProps({
  values: String
})
const state = reactive({
  ossData: {},
  editorVisible: false
})
const content = ref('')

watch(
  () => props.values,
  () => {
    content.value = props.values
  }
)

const init = reactive({
  language: 'zh-Hans',
  language_url: '/static/tinymce/langs/zh-Hans.js',
  placeholder: '在这里输入文字', //textarea中的提示信息
  min_width: 320,
  min_height: 220,
  height: 500, //注：引入autoresize插件时，此属性失效
  resize: 'both', //编辑器宽高是否可变，false-否,true-高可变，'both'-宽高均可，注意引号
  branding: false, //tiny技术支持信息是否显示
  // statusbar: false,  //最下方的元素路径和字数统计那一栏是否显示
  // elementpath: false, //元素路径是否显示
  readonly: false, //只读模式
  font_formats:
    '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;', //字体样式
  plugins:
    'print preview paste searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern emoticons', //插件配置 axupimgs indent2em
  toolbar: [
    'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | blockquote subscript superscript removeformat ',
    'styleselect formatselect fontselect fontsizeselect |  table image axupimgs media emoticons charmap hr pagebreak insertdatetime  selectall visualblocks searchreplace | code print preview | indent2em lineheight formatpainter'
  ], //工具栏配置，设为false则隐藏
  // menubar: "file edit my1", //菜单栏配置，设为false则隐藏，不配置则默认显示全部菜单，也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”

  // images_upload_url: '/apib/api-upload/uploadimg',  //后端处理程序的url，建议直接自定义上传函数image_upload_handler，这个就可以不用了
  // images_upload_base_path: '/demo',  //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.php
  paste_data_images: true, //图片是否可粘贴
  init_instance_callback: (editor) => {
    //绑定input、change事件，实时获取富文本内容
    editor.on('input', (e) => {
      emits('getValue', content.value)
    })
    editor.on('change', (e) => {
      emits('getValue', content.value)
    })
  },
  //此处为图片上传处理函数
  images_upload_handler: (blobInfo, success, failure) => {
    // debugger
    // // 这里用base64的图片形式上传图片,
    // let reader = new FileReader(); //本地预览
    // reader.readAsDataURL(blobInfo.blob());
    // reader.onloadend = function () {
    //   const imgbase64 = reader.result;
    //   success("https://fulan-edu.oss-cn-shanghai.aliyuncs.com/exerciseBook/1649820482478.jpg");
    // }
    var file = blobInfo.blob()
    const suffix = file.name.substring(file.name.lastIndexOf('.'))
    const filename = Date.now() + suffix
    // const fileData = dataURLtoFile(data)
    let formData = new FormData()
    formData.append('key', state.ossData.dir + '/' + filename)
    formData.append('OSSAccessKeyId', state.ossData.accessid)
    formData.append('policy', state.ossData.policy)
    formData.append('Signature', state.ossData.signature)
    formData.append('success_action_status', '200')
    formData.append('file', file)
    let param = {
      method: 'post',
      data: formData
    }
    axios(state.ossData.host, param).then((res) => {
      // debugger
      //https://fulan-edu.oss-cn-shanghai.aliyuncs.com/exerciseBook/1650852954042.png
      if (res.status == 200 && res.statusText?.toUpperCase() == 'OK') {
        let imgurl = `${state.ossData.host}/${state.ossData.dir}/${filename}`
        console.log('edu.oss.url==', imgurl)
        success(imgurl)
      } else {
        ElMessage.error('上传失败')
        failure('没上传好')
        console.log('edu.oss.error', res)
      }
    })
  },
  paste_data_images: true,
  images_file_types: 'jpeg,jpg,png,gif,bmp,webp',

  file_picker_types: 'file image media', //file image media分别对应三个类型文件的上传：link插件，image和axupimgs插件，media插件。想屏蔽某个插件的上传就去掉对应的参数
  // 文件上传处理函数
  file_picker_callback: function (callback, value, meta) {
    // 使用案例http://tinymce.ax-z.cn/general/upload-images.php
    // meta.filetype  //根据这个判断点击的是什么file image media

    let filetype //限制文件的上传类型,需要什么就添加什么的后缀
    if (meta.filetype == 'image') {
      filetype = '.jpg, .jpeg, .png, .gif, .ico, .svg'
    } else if (meta.filetype == 'media') {
      filetype = '.mp3, .mp4, .avi, .mov'
    } else {
      filetype =
        '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4, .jpg, .jpeg, .png, .gif, .ico, .svg'
    }
    let inputElem = document.createElement('input') //创建文件选择
    inputElem.setAttribute('type', 'file')
    inputElem.setAttribute('accept', filetype)
    inputElem.click()
    inputElem.onchange = () => {
      const fullscreenLoading = ElLoading.service({
        lock: true,
        text: '上传中，请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // debugger
      let file = inputElem.files[0] //获取文件信息

      // 所有都转成base64文件流,来自官方文档https://www.tiny.cloud/docs/configure/file-image-upload/#file_picker_callback
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = function () {
        const suffix = file.name.substring(file.name.lastIndexOf('.'))
        const filename = Date.now() + suffix
        // const fileData = dataURLtoFile(data)
        let formData = new FormData()
        formData.append('key', state.ossData.dir + '/' + filename)
        formData.append('OSSAccessKeyId', state.ossData.accessid)
        formData.append('policy', state.ossData.policy)
        formData.append('Signature', state.ossData.signature)
        formData.append('success_action_status', '200')
        formData.append('file', file)
        let param = {
          method: 'post',
          data: formData
        }
        axios(state.ossData.host, param).then((res) => {
          // debugger
          //https://fulan-edu.oss-cn-shanghai.aliyuncs.com/exerciseBook/1650852954042.png
          if (res.status == 200 && res.statusText?.toUpperCase() == 'OK') {
            let fileUrl = `${state.ossData.host}/${state.ossData.dir}/${filename}`
            console.log('edu.oss.url==', fileUrl)
            callback(fileUrl, { title: file.name })
            fullscreenLoading.close()
          } else {
            ElMessage.error('上传失败')
            console.log('edu.oss.error', res)
            fullscreenLoading.close()
          }
        })

        // Note: Now we need to register the blob in TinyMCEs image blob
        // registry. In the next release this part hopefully won't be
        // necessary, as we are looking to handle it internally.
        // let id = "blobid" + new Date().getTime();
        // let blobCache = tinymce.activeEditor.editorUpload.blobCache;
        // let base64 = reader.result.split(",")[1];
        // let blobInfo = blobCache.create(id, file, base64);
        // blobCache.add(blobInfo);

        // // call the callback and populate the Title field with the file name
        // callback(blobInfo.blobUri(), { title: file.name });
      }
    }
  }
})

onMounted(() => {
  let url = 'https://test-fulanedu-mg.fairyclass.cn/aliyun/upload/policy'
  let param = {
    method: 'get',
    data: {
      date: Date.now()
    }
  }
  request(url, param).then((res) => {
    if (res.code == 1000) {
      state.ossData = res.data
    }
  })
})

const editorChange = () => {
  // console.log(content.value)
}
</script>

<style lang="less" scoped>
.tox-statusbars {
  background: black;
}
</style>

<style lang="less">
.tox-statusbar__text-container {
  .tox-statusbar__branding {
    display: none !important;
  }
}
// .tox-tinymce-aux{
//     display: none !important;
// }
.tinymce-container > textarea {
  display: none;
}
.mce-preview-object {
  border: 1px solid #ffffff !important;
}
.tox-notification--error {
  display: none !important;
}
</style>
